<?php
namespace ac\modules\member\controllers;

use yii;
use ac\controllers\AuthController;
use app\modules\member\models\Member;
use app\modules\member\models\MemberSearch;
use common\component\exception\ErrMap;
use common\component\tool\Tool;
use common\models\OperationLog;


/*此控制器，只为后端使用*/
class MemberController extends AuthController
{
	/*列表*/
    public function actionMemberList()
    {
        if(Yii::$app->request->isPost){
            $appid = $this->post['appid']?$this->post['appid']:'';

            if(isset($this->post['page'])){
                $currPage = intval($this->post['page']?$this->post['page']:1);
            }else{
                $currPage = 1;
            }
            $pageSize = Tool::getPageSize();
            // P($appid);

            if(!empty($appid)){
                $search = (new MemberSearch())->search($this->post);
                if($search === false){//验证搜索参数不通过
                    $count = 0;
                    $memberList = array();
                }else{
                    $count = $search->where('appid = :appid', [':appid' => $appid])->count();
                    $memberList = $search->select(['memberid', 'loginname', 'phone', 'email', 'nickname', 'sex', 'headimgurl', 'curr_integral', 'cost_integral', 'lastloginip', 'lastlogin_time', 'state', 'logintimes', 'regip', 'regfrom', 'add_time'])
                                         ->where('appid = :appid', [':appid' => $appid])
                                         ->offset($pageSize*($currPage-1))->limit($pageSize)
                                         ->orderBy(['add_time' => SORT_DESC])
                                         ->asArray()->all();
                    foreach($memberList as $k => $v){
                        $memberList[$k]['lastloginip'] = long2ip($v['lastloginip']);
                        if($memberList[$k]['lastloginip'] == '0.0.0.0'){
                            $memberList[$k]['lastloginip'] = '';
                        }
                        $memberList[$k]['regip'] = long2ip($v['regip']);
                        if($v['lastlogin_time'] == '1000-01-01 00:00:00'){
                            $memberList[$k]['lastlogin_time'] = '';
                        }
                    }
                }
                $res = array(
                    'list' => $memberList,
                    'pageInfo' => array(
                        'count' => intval($count),
                        'currPage' => $currPage,
                        'pageSize' => $pageSize,
                    ),
                );
                return Tool::showRes([0, '获取成功'], $res);
            }
        }
    }

    /*综合统计*/
    public function actionMemberStatistical()
    {
        if(Yii::$app->request->isPost){
        // if(1){
        //     $this->post['appid'] = 'CMS20192xG12aUi222';
            $appid = isset($this->post['appid'])?$this->post['appid']:'';
            if(!empty($appid)){
                $gender = $this->statisticalGender($appid);
                $area = $this->statisticalArea($appid);
                $sources = $this->statisticalSources($appid);
                $login = $this->statisticalLogin($appid);
                $todayAddCount = $this->dayData($appid, date("Y-m-d", time()));//今天增加会员总数
                $yesterdayAddCount = $this->dayData($appid, date("Y-m-d", (time()-86400)));//昨天增加会员总数
                $todayLoginCount = $this->dayData($appid, date("Y-m-d", time()), 'login');//今天登录总数
                $yesterdayLoginCount = $this->dayData($appid, date("Y-m-d", (time()-86400)), 'login');//昨天登录总数
                $res  = array(
                    'gender' => $gender,
                    'area' => $area,
                    'sources' => $sources,
                    'login' => $login,
                    'day' => array(
                        'todayAddCount' => $todayAddCount,
                        'yesterdayAddCount' => $yesterdayAddCount,
                        'todayLoginCount' => $todayLoginCount,
                        'yesterdayLoginCount' => $yesterdayLoginCount,
                    ),
                );
                // P($day);
                return Tool::showRes([0, '获取成功'], $res);
            }
        }
        return Tool::showRes(ErrMap::getError(10005));
    }

    /*
    当日数据
    $day    当天日期 格式为 2020-07-02
    $flag   add(注册用户总数)  login(登录总数)  integralAdd(增加积分总数)  integral1Reduction(减少积分总数)
    */
    private function dayData($appid, $day, $flag = 'add')
    {
        $member = new Member;
        if($flag == 'add'){
            $count = $member::find()
                        ->where("add_time > '{$day}' and add_time < '{$day} 23:59:59' and appid = :appid", [':appid' => $appid])
                        ->count();
        }
        if($flag == 'login'){
            $count = $member::find()
                        ->where("lastlogin_time > '{$day}' and lastlogin_time < '{$day} 23:59:59' and appid = :appid", [':appid' => $appid])
                        ->count();
        }
        return $count;
    }

    /*统计 性别*/
    private function statisticalGender($appid)
    {
        $sql = "select sex, count(sex) as num from {{%member}} where appid = :appid group by sex";
        $res = Member::findBySql($sql, [':appid' => $appid])->asArray()->all();
        $gender = [];
        foreach($res as $k => $v){
            if($v['sex'] == 0){//保密
                $gender['secret'] = $v['num'];
            };
            if($v['sex'] == 1){//男
                $gender['male'] = $v['num'];
            };
            if($v['sex'] == 2){//女
                $gender['female'] = $v['num'];
            };
        }
        return $gender;
    }

    /*统计 地域*/
    private function statisticalArea($appid)
    {
        $sql = "select province, count(province) as num from {{%member}} where appid = :appid group by province";
        $res = Member::findBySql($sql, [':appid' => $appid])->asArray()->all();
        $area = [];
        foreach($res as $k => $v){
            switch ($v['province']) {
                case '110000':
                    $area['北京'] = $v['num'];
                    break;
                case '120000':
                    $area['天津'] = $v['num'];
                    break;
                case '130000':
                    $area['河北'] = $v['num'];
                    break;
                case '140000':
                    $area['山西'] = $v['num'];
                    break;
                case '150000':
                    $area['内蒙古'] = $v['num'];
                    break;
                case '210000':
                    $area['辽宁'] = $v['num'];
                    break;
                case '220000':
                    $area['吉林'] = $v['num'];
                    break;
                case '230000':
                    $area['黑龙江'] = $v['num'];
                    break;
                case '310000':
                    $area['上海'] = $v['num'];
                    break;
                case '320000':
                    $area['江苏'] = $v['num'];
                    break;
                case '330000':
                    $area['浙江'] = $v['num'];
                    break;
                case '340000':
                    $area['安徽'] = $v['num'];
                    break;
                case '350000':
                    $area['福建'] = $v['num'];
                    break;
                case '360000':
                    $area['江西'] = $v['num'];
                    break;
                case '370000':
                    $area['山东'] = $v['num'];
                    break;
                case '410000':
                    $area['河南'] = $v['num'];
                    break;
                case '420000':
                    $area['湖北'] = $v['num'];
                    break;
                case '430000':
                    $area['湖南'] = $v['num'];
                    break;
                case '440000':
                    $area['广东'] = $v['num'];
                    break;
                case '450000':
                    $area['广西'] = $v['num'];
                    break;
                case '460000':
                    $area['海南'] = $v['num'];
                    break;
                case '500000':
                    $area['重庆'] = $v['num'];
                    break;
                case '510000':
                    $area['四川'] = $v['num'];
                    break;
                case '520000':
                    $area['贵州'] = $v['num'];
                    break;
                case '530000':
                    $area['云南'] = $v['num'];
                    break;
                case '540000':
                    $area['西藏'] = $v['num'];
                    break;
                case '610000':
                    $area['陕西'] = $v['num'];
                    break;
                case '620000':
                    $area['甘肃'] = $v['num'];
                    break;
                case '630000':
                    $area['青海'] = $v['num'];
                    break;
                case '640000':
                    $area['宁夏'] = $v['num'];
                    break;
                case '650000':
                    $area['新疆'] = $v['num'];
                    break;
                case '710000':
                    $area['台湾'] = $v['num'];
                    break;
                case '810000':
                    $area['香港'] = $v['num'];
                    break;
                case '820000':
                    $area['澳门'] = $v['num'];
                    break;
                default:
                    # code...
                    break;
            }
        }
        return $area;
    }

    /*统计 来源*/
    private function statisticalSources($appid)
    {
        $sql = "select regfrom, count(regfrom) as num from {{%member}} where appid = :appid group by regfrom";
        $res = Member::findBySql($sql, [':appid' => $appid])->asArray()->all();
        $sources = [];
        foreach($res as $k => $v){
            if($v['regfrom'] == 1){//后台
                $sources['backend'] = $v['num'];
            };
            if($v['regfrom'] == 2){//PC
                $sources['pc'] = $v['num'];
            };
            if($v['regfrom'] == 3){//移动
                $sources['mobile'] = $v['num'];
            };
        }
        return $sources;
    }

    /*统计 登录频率*/
    private function statisticalLogin($appid)
    {
        /*注释原因，之前没有loginfrequency字段，此sql可以算出用户的具体登录频率，包括小数点*/
        // $sql = "select logintimes/round((unix_timestamp(now())-unix_timestamp(add_time))/86400) as frequency, logintimes from {{%member}} where appid = :appid";
        $sql = "select loginfrequency, count(loginfrequency) as num from {{%member}} where appid = :appid group by loginfrequency";
        $login = [];
        $res = Member::findBySql($sql, [':appid' => $appid])->asArray()->all();
        foreach($res as $k => $v){
            $login[$v['loginfrequency']] = $v['num'];
        }
        return $login;
    }

}
